﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace Inovout.Web.Mvc
{
    public class XmlResult : ActionResult
    {

        public Encoding ContentEncoding { get; set; }

        public string ContentType { get; set; }

        public object Data { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                XmlSerializer xmlSerializer = new XmlSerializer(Data.GetType());
                using (StringWriter sringWriter = new StringWriter())
                {
                    xmlSerializer.Serialize(sringWriter, Data);
                    response.Write(sringWriter.ToString());
                }
            }
        }
    }
}
